<template>
    <div class="logic-flow">
        <div ref="containerRef" id="container" class="viewport"></div>
        <TeleportContainer />            
        <el-button type="primary" @click="getFlowData" style="position: absolute; top:50px; left:200px;">获取流程数据</el-button>
        <UserEditNode ref="userEditNodeRef" @confirmNode="(data:NodeDataType)=>confirmEditNode(data)" @closeNode="(id:string) => closeNodeCallback(id)"/>    
    </div>
</template>
  
<script setup lang="ts">
import { onMounted, ref } from 'vue'
import LogicFlow from '@logicflow/core'
import '@logicflow/core/es/index.css'
import "@logicflow/extension/lib/style/index.css"
import { SelectionSelect } from "@logicflow/extension"


import { getTeleport } from '@logicflow/vue-node-registry'

import UserEditNode from './FlowConfig/index.vue' // 引入 UserEditNode 组件
import type { NodeDataType } from './FlowConfig/index.vue'

//引入自定义类
import { CustomDndPanel } from './LFTool/custom-dnd-panel'
import setCustomDndPanel from './LFTool/custom-dnd-panel/setCustomDndPanel/setCustomDndPanel'
import setEventsListener from './eventsListener'
import setRegister from './register'
import './LFTool/custom-dnd-panel/panelStyle.scss'
import { CustomControl } from './LFTool/custom-control'
import './LFTool/custom-control/control.scss'
import { CustomMenu } from './LFTool/custom-menu'
import './LFTool/custom-menu/menu.scss'
import { calcWordWidth } from '@/utils/calcWordWidth';
import { v4 as uuidv4 } from 'uuid';

const userEditNodeRef = ref();
const containerRef = ref<HTMLDivElement | null>(null)
const TeleportContainer = getTeleport()
let lf: any;
let isKeyUp = true;
const generateUniqueId = (type: string):string => {
    const uniqueId = uuidv4();
    return `${type}-${uniqueId}`;
}
const getFlowData = () => {
    // const data = lf.getGraphData();
    // const id = generateUniqueId('node');
    // console.log(data);
}
const confirmEditNode = (data: NodeDataType) => {    
    if(data.type !='custom-edge'){
        lf.setProperties(data.id,{
            customNodeCode: data.code,
            customNodeName: data.name,
        })    
    }else if(data.type == 'custom-edge'){
        let textWidth = 38;
        if(data.name){
            textWidth = calcWordWidth(data.name) + 14;            
        }        
        if(data.associatedId){
            lf.setProperties(data.id,{                
                customNodeName: data.name,
            })
            const nodeModel = lf.getNodeModelById(data.associatedId)
            const x = nodeModel.x
            const width  = nodeModel.properties.width            
            lf.setProperties(data.associatedId,{                
                customNodeName: data.name,
                width: textWidth,
            })
            nodeModel.x = x + (textWidth - width)/2            
        }else{
            const id = generateUniqueId('custom-edge');
            let x=0;
            let y=0;
            if(data.direction === 'bottom'){
                x = data.position.x + 24 + (textWidth - 38)/2;
                y = data.position.y + 20;
            }else if(data.direction === 'top'){
                x = data.position.x + 24 + (textWidth - 38)/2;
                y = data.position.y - 20;
            }else if(data.direction === 'right'){
                x = data.position.x + 24 + (textWidth - 38)/2;
                y = data.position.y - 20;
            }else if(data.direction === 'left'){
                x = data.position.x - 24 - (textWidth - 38)/2;
                y = data.position.y - 20;
            }        
            lf.addNode({
                id:id,
                type: 'custText',
                x: x,
                y: y,
                resizable: true,
                properties: {
                    width: textWidth,
                    height: 28,                    
                    customNodeName: data.name,
                    associatedId: data.id,         
                }
            })
            lf.setProperties(data.id,{                
                customNodeName: data.name,
                associatedId: id,
            })
        }                   
    }
}
    
const closeNodeCallback = (_id: string) => {
    const graphElement = containerRef.value?.querySelector('div')    
    if (graphElement) {
       graphElement.focus();      
    }
}
// const handleDbClick = (event: any, element: any) => {
//     if (event.target === element) {
//         const rect = element.getBoundingClientRect();
//         const graphTransform = lf.getTransform();
//         const x = event.clientX - rect.left - graphTransform.TRANSLATE_X;
//         const y = event.clientY - rect.top - graphTransform.TRANSLATE_Y;
//         const id = generateUniqueId('node');
//         lf.addNode({
//             id:id,
//             type: 'custText',
//             x: x,
//             y: y,
//             resizable: true,
//             properties: {
//                 width: 38,
//                 height: 28,
//                 customNodeName: '同意',
//             }
//         })
//         lf.selectElementById(id,false,true);
//     }
// }
onMounted(() => {
    if (containerRef.value) {
        lf = new LogicFlow({
            container: containerRef.value,
            nodeTextEdit: false,
            edgeTextEdit: false,
            plugins: [SelectionSelect,CustomDndPanel,CustomControl,CustomMenu],
            background: {
                backgroundColor: 'var(--el-bg-color-overlay)'
            },
            keyboard: {
                enabled: true,
                shortcuts: [
                    {
                        keys: ["del"],
                        callback: () => {
                            const elements = lf.getSelectElements(true);
                            lf.clearSelectElements();
                            elements.edges.forEach((edge:any) => lf.deleteEdge(edge.id));
                            elements.nodes.forEach((node:any) => lf.deleteNode(node.id));
                        },
                    },
                    {
                        keys: ["backspace"],
                        callback: () => {                            
                        },
                    },
                    {
                        keys: ["ctrl"],
                        action: "keydown",
                        callback: () => {                                                    
                            if(isKeyUp){
                                lf.openSelectionSelect();
                                isKeyUp = false;
                            }
                        },
                    },
                    {
                        keys: ["ctrl"],
                        action: "keyup",
                        callback: () => {
                            lf.closeSelectionSelect();                           
                            isKeyUp = true;
                        },
                    },
                ],
            },
            // grid: true,
        })
        lf.setTheme({
            snapline: {
                strokeDasharray: "3,3",
                // stroke: 'var(--el-color-primary-light-3)', // 对齐线颜色
                strokeWidth: 1, // 对齐线宽度
            },            
        })      
        
        // 注册事件
        setRegister(lf);     
        lf.render({});
        //设置拖拽面板
        setCustomDndPanel(lf);
        // 监听事件
        setEventsListener(lf,{userEditNodeRef:userEditNodeRef})
        
     
        // const graphBackGroundElement = containerRef.value.querySelector('.lf-canvas-overlay')
        // if(graphBackGroundElement){
        //     graphBackGroundElement.addEventListener("dblclick", (event) => handleDbClick(event,graphBackGroundElement));  
        // }      
    }
})
</script>
<style scoped lang="scss">
.logic-flow{
    height: 100%;
    width: 100%;
    position: relative;
}
:deep(g.cust-text-node-content){
    g.lf-anchor{
        display: none;
    }
}
#container {
    width: 100%;
    height: 100%
}
</style>
